from import_export import widgets
from .models import DictData


class DictDataLabelWidget(widgets.Widget):

    def __init__(self, dict_type=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.dict_type = dict_type

    def clean(self, value, row=None, *args, **kwargs):

        if not value:
            return None

        try:
            return DictData.objects.get(type=self.dict_type, label=value).value
        except DictData.DoesNotExist:
            raise ValueError(
                f"No DictData found with type={self.dict_type} and label={value}"
            )
